function add() {
	var validate = $('#form1').validate({
		rules : {
			name: {required:true,
				remote: {
					url: "/userGroup/vName",     //后台处理程序
					type: "post",               //数据发送方式
					dataType: "json",           //接受数据格式
					data: {                     //要传递的数据
						id: $("#entityId").val()
					}
				},
				maxlength:50
			},
			description: {maxlength:100},
			enabled: {required:true}
		},
		messages: {
			name: {required:"必填字段!", remote: "用户组已存在!",maxlength:"最多可以输入{0}个字符!"},
			description: {maxlength:"最多可以输入{0}个字符!"},
			enabled: {required:"必填字段!"}
		},
		highlight : function(element) {
// 				$(element).parent('td').find('label').before('<br>');
		},
		success : function(element) {
		}
	});
	$('#form1').submit();
}

$(function() {
	//返回按钮
	$('#btnBack').on({
		  click: function() {
			  $("#backForm").submit();
		  }
	});

	$.validator.addMethod('deptNumber', function(value, element) {
		var regex = /^[\d|\.]*$/;
		return regex.test(value);
	});
	//字符和数字
	$.validator.addMethod('numberAndLetter', function(value, element) {
		var regex = /^[a-zA-Z0-9]*$/;
		return regex.test(value);
	});
})

$(document).ready(function() {
	/**
	 $('ul#plPagination').page(parseInt($("input[name=plPage]").val()), parseInt($("input[name=plRows]").val()), parseInt($("#plTotal").val()), false, function(cp) {
		 queryPl(cp);
	 });
	 **/
	var plPage = $("input[name=plPage]").val();
	var plRows = $("input[name=plRows]").val();
	var plTotal = $("#plTotal").val();
	$('ul#plPagination').page({
		"curPage": parseInt(plPage),
		"pageSize": parseInt(plRows),
		"totalCount": parseInt(plTotal),
		"init": true,
		"callback": function (page) {
			queryPl(page);
		}
	});

	 $('#btnPlRm').on('click', function() {
		 var checked = $('#plListTable input:checkbox:checked');
			if (checked.length == 0) {
				alert('请选择产品线!');
				return;
			}
			var ids = "";
			for(var i = 0; i < checked.length; i++) {
				ids += $(checked[i]).val() + ",";
			}

			$.ajax({
    			type:'post',
    			url:'/userGroup/deletePermission',
    			data:{ids:ids},
    			success:function(data) {
    				if (!data.success) {
    					alert(data.reason);
    				} else {
    					$('#addPl').modal('hide');
    					$('#tabForm input[name=tab]').val('pl');
    					$('#tabForm').submit();
    				}
    			}
    		});
	});

	    //选择产品线
		$("#plTable").on('click', 'tr', function(){
			var checkbox = $(this).children("td").children("input[type='checkbox']");
			checkbox.click();
		});

		$("#plTable").on('click', 'tr td input', function(event){
			//阻止冒泡事件
			event.stopPropagation();
		});

		//已经选择的产品线
		$("#plListTable tr").on('click', function(){
			var checkbox = $(this).children("td").children("input[type='checkbox']");
			checkbox.click();
		});

		$("#plListTable tr td input").on('click', function(event){
			//阻止冒泡事件
			event.stopPropagation();
		});

		//全选/反选按钮,已经存在的列表
		$('#checkPlListAll').on(
			  'click',function() {
					if ($('#checkPlListAll').is(':checked')) {
						 $("#plListTable").find("input[type='checkbox']:visible").each(function () {
							 //只对可见的操作
							$(this).prop("checked", "checked");

						});
					}else {
						 $("#plListTable").find("input[type='checkbox']:visible").each(function () {
							 //只对可见的操作
							$(this).removeAttr("checked");
						});
					}
			  }
		);

		//全选/反选按钮 查询列表
		$('#selectPlListAll').on(
			  'click',function() {
					if ($('#selectPlListAll').is(':checked')) {
						 $("#plTable").find("input[type='checkbox']:visible").each(function () {
							 //只对可见的操作
							$(this).prop("checked", "checked");

						});
					}else {
						 $("#plTable").find("input[type='checkbox']:visible").each(function () {
							 //只对可见的操作
							$(this).removeAttr("checked");
						});
					}
			  }
		);

	 $('#queryPL').on('click', function() {
		 $.ajax({
    			type:'post',
    			url:'/listEntry/selectJoinLevelProductLine',
    			data:{
    				page:1,
    				rows:500,
    				entryValue:$('div#addPl #productLineName').val(),
					enabled:$('div#addPl #enabled').val(),
    			},
    			success:function(data) {
    				$('#plTable').empty();
    				var rows = data.rows;
    				for(var i = 0; i < rows.length; i++) {
    					var p = rows[i];
    					var tr = $('<tr/>');
    					if (i%2 == 1) {
    						tr = $('<tr bgcolor="#f2f2f2">');
    					}
    					$('<td align="center"/>').append('<input type="checkbox" value="'+ p.id +'"/>').append(i+1).appendTo(tr);
    					$('<td/>').text(p.entryValue).appendTo(tr);
						if(p.enabled==1) {
							$('<td/>').text('启用').appendTo(tr);
						}else if(p.enabled==0){
							$('<td/>').text('禁用').appendTo(tr);
						}else{
							$('<td/>').text('状态不明').appendTo(tr);
						}
						tr.appendTo($('#plTable'));
    				}
    			}
    		});
	});

	 $('#resetPL').on('click', function() {
		 $('div#addPl #productLineName').val('');
		 $('div#addPl input:text,select').val('');
	 });

	 $('#batchSavePl').on('click', function() {
		 var checked = $('#plTable input:checkbox:checked');
			if (checked.length == 0) {
				alert('请选择产品线!');
				return;
			}
			var ids = "";
			for(var i = 0; i < checked.length; i++) {
				ids += $(checked[i]).val() + ";";
			}

			//添加权限
			$.ajax({
				type : 'post',
				url : '/userGroup/batchAddPermission',
				data : {
					userGroupId : $("#entityId").val(),
					type : 1,
					permissionIds : ids
				},
				success : function(data) {
					if (!data.success) {
						alert(data.reason);
					} else {
						$('#addPl').modal('hide');
    					$('#tabForm input[name=tab]').val('pl');
    					$('#tabForm').submit();
					}
				}
			});
	});


	$('ul#projectPagination').page(parseInt($("input[name=pPage]").val()), parseInt($("input[name=pRows]").val()), parseInt($("#projectTotal").val()), false, function(cp) {
		queryProject(cp);
	 });

	$.fn.modal.Constructor.prototype.enforceFocus = function () {};

	initSelect2();

	$('.btn-Project-reset').on('click', function() {
		$('#projectNumber').val('');
		$('#addProject #name').val('');
		$('#pm,#productLine').empty();
		initSelect2();
	});

	$('.btn-query').on('click', function() {
		$.ajax({
			type:'post',
			url:'/project/data',
			data:{
				page:1,
				rows:100,
				projectNumber:$('#projectNumber').val(),
				name:$('#addProject #name').val(),
				pm:$('#pm').val(),
				productLine:$('#productLine').val()
			},
			success:function(data) {
				$('#projectTable').empty();
				var rows = data.rows;
				for(var i = 0; i < rows.length; i++) {
					var p = rows[i];
					var tr = $('<tr/>');
					if (i%2 == 1) {
						tr = $('<tr bgcolor="#f2f2f2">');
					}
					$('<td align="center"/>').append('<input type="checkbox" value="'+ p.id +'"/>').append(i+1).appendTo(tr);
					$('<td/>').text(p.projectNumber).appendTo(tr);
					$('<td/>').text(p.name).appendTo(tr);
					$('<td align="center"/>').text(p.pmName).appendTo(tr);
					$('<td/>').text(p.productLine).appendTo(tr);
					tr.appendTo($('#projectTable'));
				}
			}
		});
	});

    //选择产品线
	$("#projectTable").on('click', 'tr', function(){
		var checkbox = $(this).children("td").children("input[type='checkbox']");
		checkbox.click();
	});

	$("#projectTable").on('click', 'tr td input', function(event){
		//阻止冒泡事件
		event.stopPropagation();
	});

	//已经选择的产品线
	$("#projectListTable tr").on('click', function(){
		var checkbox = $(this).children("td").children("input[type='checkbox']");
		checkbox.click();
	});

	$("#projectListTable tr td input").on('click', function(event){
		//阻止冒泡事件
		event.stopPropagation();
	});

	//全选/反选按钮,已经存在的列表
	$('#checkProjectListtAll').on(
		  'click',function() {
				if ($('#checkProjectListtAll').is(':checked')) {
					 $("#projectListTable").find("input[type='checkbox']:visible").each(function () {
						 //只对可见的操作
						$(this).prop("checked", "checked");

					});
				}else {
					 $("#projectListTable").find("input[type='checkbox']:visible").each(function () {
						 //只对可见的操作
						$(this).removeAttr("checked");
					});
				}
		  }
	);

	//全选/反选按钮 查询列表
	$('#selectProjectListAll').on(
		  'click',function() {
				if ($('#selectProjectListAll').is(':checked')) {
					 $("#projectTable").find("input[type='checkbox']:visible").each(function () {
						 //只对可见的操作
						$(this).prop("checked", "checked");

					});
				}else {
					 $("#projectTable").find("input[type='checkbox']:visible").each(function () {
						 //只对可见的操作
						$(this).removeAttr("checked");
					});
				}
		  }
	);


	$('#projectSave').on('click', function() {
		 var checked = $('#projectTable input:checkbox:checked');
			if (checked.length == 0) {
				alert('请选择项目!');
				return;
			}
			var ids = "";
			for(var i = 0; i < checked.length; i++) {
				ids += $(checked[i]).val() + ";";
			}

			//添加权限
			$.ajax({
				type : 'post',
				url : '/userGroup/batchAddPermission',
				data : {
					userGroupId : $("#entityId").val(),
					type : 2,
					permissionIds : ids
				},
				success : function(data) {
					if (!data.success) {
						alert(data.reason);
					} else {
						$('#addRole').modal('hide');
    					$('#tabForm input[name=tab]').val('project');
    					$('#tabForm').submit();
					}
				}
			});
	});

	$('#btnProjectRm').on('click', function() {
		 var checked = $('#projectListTable input:checkbox:checked');
			if (checked.length == 0) {
				alert('请选择项目!');
				return;
			}
			var ids = "";
			for(var i = 0; i < checked.length; i++) {
				ids += $(checked[i]).val() + ",";
			}

			$.ajax({
    			type:'post',
    			url:'/userGroup/deletePermission',
    			data:{ids:ids},
    			success:function(data) {
    				if (!data.success) {
    					alert(data.reason);
    				} else {
    					$('#addRole').modal('hide');
    					$('#tabForm input[name=tab]').val('project');
    					$('#tabForm').submit();
    				}
    			}
    		});
	});

	//角色分页
	//  $('ul#rolePagination').page(parseInt($("input[name=rPage]").val()), parseInt($("input[name=rRows]").val()), parseInt($("#roleTotal").val()), false, function(cp) {
	// 	 query(cp);
	//  });
	var rPage = $("input[name=rPage]").val();
	var rRows = $("input[name=rRows]").val();
	var roleTotal = $("#roleTotal").val();
	$('ul#rolePagination').page({
		"curPage": parseInt(rPage),
		"pageSize": parseInt(rRows),
		"totalCount": parseInt(roleTotal),
		"init": true,
		"callback": function (page) {
			queryRole(page);
		}
	});

	//查询角色
	 $('#queryRole').on('click', function() {
			$.ajax({
				type:'post',
				url:'/role/data',
				data:{
					page:1,
					rows:100,
					name:$('div#addRole #name').val(),
					description:$('div#addRole #description').val()
				},
				success:function(data) {
					$('#roleTable').empty();
					var rows = data.rows;
					for(var i = 0; i < rows.length; i++) {
						var p = rows[i];
						var tr = $('<tr/>');
						if (i%2 == 1) {
							tr = $('<tr bgcolor="#f2f2f2">');
						}
						$('<td align="center"/>').append('<input type="checkbox" value="'+ p.id +'"/>').append(i+1).appendTo(tr);
						$('<td/>').text($.trim(p.name)).appendTo(tr);
						$('<td/>').text($.trim(p.description)).appendTo(tr);
						if (p.enabled == 1) {
							$('<td/>').text('启用').appendTo(tr);
						} else {
							$('<td/>').text('禁用').appendTo(tr);
						}
						tr.appendTo($('#roleTable'));
					}
				}
			});
		});

	//选择角色
	$("#roleTable").on('click', 'tr', function(){
		var checkbox = $(this).children("td").children("input[type='checkbox']");
		checkbox.click();
	});

	$("#roleTable").on('click', 'tr td input', function(event){
		//阻止冒泡事件
		event.stopPropagation();
	});

	//已经选择的角色
	$("#roleListTable tr").on('click', function(){
		var checkbox = $(this).children("td").children("input[type='checkbox']");
		checkbox.click();
	});

	$("#roleListTable tr td input").on('click', function(event){
		//阻止冒泡事件
		event.stopPropagation();
	});

	//全选/反选按钮,已经存在的角色列表
	$('#checkRoleListAll').on(
		'click',function() {
			if ($('#checkRoleListAll').is(':checked')) {
				$("#roleListTable").find("input[type='checkbox']:visible").each(function () {
					//只对可见的操作
					$(this).prop("checked", "checked");

				});
			}else {
				$("#roleListTable").find("input[type='checkbox']:visible").each(function () {
					//只对可见的操作
					$(this).removeAttr("checked");
				});
			}
		}
	);

	//全选/反选按钮 角色查询列表
	$('#selectRoleListAll').on(
		'click',function() {
			if ($('#selectRoleListAll').is(':checked')) {
				$("#roleTable").find("input[type='checkbox']:visible").each(function () {
					//只对可见的操作
					$(this).prop("checked", "checked");

				});
			}else {
				$("#roleTable").find("input[type='checkbox']:visible").each(function () {
					//只对可见的操作
					$(this).removeAttr("checked");
				});
			}
		}
	);

	$('#resetRole').on('click', function() {
		$('div#addRole input:text,select').val('');
	});

	//保存角色
	$('#batchSaveRole').on('click', function() {
		var checked = $('#roleTable input:checkbox:checked');
		if (checked.length == 0) {
			alert('请选择角色!');
			return;
		}
		var ids = "";
		for(var i = 0; i < checked.length; i++) {
			ids += $(checked[i]).val() + ";";
		}
		//添加角色
		$.ajax({
			type : 'post',
			url : '/userGroup/batchAddRole',
			data : {
				userGroupId : $("#entityId").val(),
				roleIds : ids
			},
			success : function(data) {
				if (!data.success) {
					alert(data.reason);
				} else {
					$('#addRole').modal('hide');
					$('#tabForm input[name=tab]').val('roles');
					$('#tabForm').submit();
				}
			}
		});
	});
	//删除角色
	$('#btnRoleRm').on('click', function() {
		var checked = $('#roleListTable input:checkbox:checked');
		if (checked.length == 0) {
			alert('请选择角色!');
			return;
		}
		var ids = "";
		for(var i = 0; i < checked.length; i++) {
			ids += $(checked[i]).val() + ",";
		}
		//删除角色
		$.ajax({
			type:'post',
			url:'userGroup/batchDeleteRole',
			data:{roleIds:ids, userGroupId:$("#entityId").val()},
			success:function(data) {
				if (!data.success) {
					alert(data.reason);
				} else {
					$('#addRole').modal('hide');
					$('#tabForm input[name=tab]').val('roles');
					$('#tabForm').submit();
				}
			}
		});
	});


	// $('ul#userPagination').page(parseInt($("input[name=uPage]").val()), parseInt($("input[name=uRows]").val()), parseInt($("#userTotal").val()), false, function(cp) {
	// 	queryUser(cp);
	// });

	var uPage = $("input[name=uPage]").val();
	var uRows = $("input[name=uRows]").val();
	var userTotal = $("#userTotal").val();
	$('ul#userPagination').page({
		"curPage": parseInt(uPage),
		"pageSize": parseInt(uRows),
		"totalCount": parseInt(userTotal),
		"init": true,
		"callback": function (page) {
			queryUser(page);
		}
	});

	$('#queryUser').on('click', function() {
		$.ajax({
			type:'post',
			url:'/user/data',
			data:{
				page:1,
				rows:100,
				loginId:$('div#addUser #loginId').val(),
				userName:$('div#addUser #userName').val(),
				deptName:$('div#addUser #deptName').val(),
				enabled:$('div#addUser #enabled').val()
			},
			success:function(data) {
				$('#userTable').empty();
				var rows = data.rows;
				for(var i = 0; i < rows.length; i++) {
					var p = rows[i];
					var tr = $('<tr/>');
					if (i%2 == 1) {
						tr = $('<tr bgcolor="#f2f2f2">');
					}
					$('<td align="center"/>').append('<input type="checkbox" value="'+ p.id +'"/>').append(i+1).appendTo(tr);

					$('<td/>').text(p.loginId).appendTo(tr);
					$('<td/>').text($.trim(p.userName)).appendTo(tr);
					$('<td/>').text($.trim(p.deptName)).appendTo(tr);

					if (p.enabled == 1) {
						$('<td/>').text('启用').appendTo(tr);
					} else {
						$('<td/>').text('禁用').appendTo(tr);
					}
					tr.appendTo($('#userTable'));
				}
			}
		});
	});

	//选择用户
	$("#userTable").on('click', 'tr', function(){
		var checkbox = $(this).children("td").children("input[type='checkbox']");
		checkbox.click();
	});

	$("#userTable").on('click', 'tr td input', function(event){
		//阻止冒泡事件
		event.stopPropagation();
	});

	//已经选择的用户
	$("#userListTable tr").on('click', function(){
		var checkbox = $(this).children("td").children("input[type='checkbox']");
		checkbox.click();
	});

	$("#userListTable tr td input").on('click', function(event){
		//阻止冒泡事件
		event.stopPropagation();
	});


	//全选/反选按钮,已经存在的列表
	$('#checkUserListAll').on(
		'click',function() {
			if ($('#checkUserListAll').is(':checked')) {
				$("#userListTable").find("input[type='checkbox']:visible").each(function () {
					//只对可见的操作
					$(this).prop("checked", "checked");

				});
			}else {
				$("#userListTable").find("input[type='checkbox']:visible").each(function () {
					//只对可见的操作
					$(this).removeAttr("checked");
				});
			}
		}
	);

	//全选/反选按钮 查询列表
	$('#selectUserListAll').on(
		'click',function() {
			if ($('#selectUserListAll').is(':checked')) {
				$("#userTable").find("input[type='checkbox']:visible").each(function () {
					//只对可见的操作
					$(this).prop("checked", "checked");

				});
			}else {
				$("#userTable").find("input[type='checkbox']:visible").each(function () {
					//只对可见的操作
					$(this).removeAttr("checked");
				});
			}
		}
	);

	$('#resetUser').on('click', function() {
		$('div#addUser input:text,select').val('');
	});

	$('#batchSave').on('click', function() {
		var checked = $('#userTable input:checkbox:checked');
		if (checked.length == 0) {
			alert('请选择用户!');
			return;
		}
		var ids = "";
		for(var i = 0; i < checked.length; i++) {
			ids += $(checked[i]).val() + ";";
		}

		$.ajax({
			type:'post',
			url:'/userGroup/saveBatchUserForUserGroup',
			data:{userIds:ids,userGroupId:$("#entityId").val()},
			success:function(data) {
				if (!data.success) {
					alert(data.reason);
				} else {
					$('#addUser').modal('hide');
					$('#tabForm input[name=tab]').val('users');
					$('#tabForm').submit();
				}
			}
		});
	});



	$('#btnUserRm').on('click', function() {
		var checked = $('#userListTable input:checkbox:checked');
		if (checked.length == 0) {
			alert('请选择是删除的用户!');
			return;
		}
		var ids = "";
		for(var i = 0; i < checked.length; i++) {
			ids += $(checked[i]).val() + ",";
		}
		$.ajax({
			type:'post',
			url:'/userGroup/deleteUser',
			data:{userIds:ids,userGroupId:$("#entityId").val()},
			success:function(data) {
				if (!data.success) {
					alert(data.reason);
				} else {
					$('#tabForm input[name=tab]').val('users');
					$('#tabForm').submit();
				}
			}
		});
	});
});

function queryPl(cp) {
	$('#tabForm input:hidden[name=tab]').val('pl');
	$('#tabForm input:hidden[name=plPage]').val(cp);
	$('#tabForm input:hidden[name=plRows]').val(parseInt($("input[name=plRows]").val()));
	$('#tabForm').submit();
}

//初始化select2控件
function initSelect2(){
	$("#pm").select2({
		language : "zh-CN",
		placeholder : '请选择',
		allowClear : true,
		width : '220px',
		minimumInputLength : 1,
		ajax : {
			type: "POST",
			url : "/user/data",
			dataType : 'json',
			delay : 250,
			data : function(params) {
				return {
					qLoginIdOrUserName : params.term,
					page : params.page ? params.page : 1,
					rows : 10
				};
			},
			processResults : function(data, params) {
				var results = [];
				$.each(data.rows, function(i, v) {
					var o = {};
					//因为项目中PM保存的是工号，不是ID
					o.id = v.loginId;
					o.text = v.showName;
					o.deptName = v.deptName;
					results.push(o);
				})

				params.page = params.page || 1;
				return {
					results : results,
					pagination : {
						more : (params.page * 10) < data.total
					}
				};
			},
			cache : false
		},
		escapeMarkup: function (markup) { return markup; },
		templateResult: formatUserRepo,
		templateSelection: formatUserRepoSelection
	});

	$("#productLine").select2({
		language : "zh-CN",
		placeholder : '请选择',
		allowClear : true,
		width : '220px',
		minimumInputLength : 1,
		ajax : {
			url : "/listEntry/selectJoinLevelProductLine",
			dataType : 'json',
			type:'post',
			delay : 250,
			data : function(params) {
				return {
					entryValue : params.term,
					page : params.page ? params.page : 1,
					rows : 10
				};
			},
			processResults : function(data, params) {
				var results = [];
				$.each(data.rows, function(i, v) {
					var o = {};
					o.id = v.id;
					o.text = v.entryValue;
					results.push(o);
				});

				params.page = params.page || 1;
				return {
					results : results,
					pagination : {
						more : (params.page * 10) < data.total
					}
				};
			},
			cache : false
		}
	});
}

function queryProject(cp) {
	$('#tabForm input:hidden[name=tab]').val('project');
	$('#tabForm input:hidden[name=pPage]').val(cp);
	$('#tabForm input:hidden[name=pRows]').val($("input[name=pRows]").val());
	$('#tabForm').submit();
}

function queryUser(cp) {
	$('#tabForm input:hidden[name=tab]').val('users');
	$('#tabForm input:hidden[name=uPage]').val(cp);
	$('#tabForm input:hidden[name=uRows]').val(10);
	$('#tabForm').submit();
}

function queryRole(cp) {
	$('#tabForm input:hidden[name=tab]').val('roles');
	$('#tabForm input:hidden[name=rPage]').val(cp);
	$('#tabForm input:hidden[name=rRows]').val(10);
	$('#tabForm').submit();
}